<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Auth,Cache;
class GetMenu
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $permission_id = db::table('roles')->where('id',Auth::user()->role_id)->value('permission_id');
        $arr = explode(",",$permission_id);
        //一级菜单
        $map1[] = array('is_show','1');
        $map1[] = array('cid','0');
        if(Auth::guard('admin')->user()->id === 1){
            $menu1 = DB::table('permissions')->where($map1)->orderBy('paixu', 'asc')->get();
        }else{
            $menu1 = DB::table('permissions')->where($map1)->orderBy('paixu', 'asc')->whereIn('id',$arr)->get();
        }

        //二级菜单
        $map2[] = array('is_show','1');
        $map2[] = array('cid','<>','0');
        if(Auth::guard('admin')->user()->id === 1){
            $menu2 = DB::table('permissions')->where($map2)->orderBy('paixu', 'asc')->get();
        }else{
            $menu2 = DB::table('permissions')->where($map2)->orderBy('paixu', 'asc')->whereIn('id',$arr)->get();
        }

        //左侧菜单
        $area_id = Auth::user()->area_id;
        $arr2 = explode(",",$area_id);

        if(Auth::guard('admin')->user()->dengji === 1){
            $area1 = db::table('area')->where('dengji','=','1')->orderby('paixu')->get();
        }else{
            $area1 = db::table('area')->where('dengji','=','1')->orderby('paixu')->whereIn('id',$arr2)->get();
        }

        if(Auth::guard('admin')->user()->dengji === 1){
            $area2 = db::table('area')->where('dengji','=','2')->orderby('paixu')->get();
        }else{
            $area2 = db::table('area')->where('dengji','=','2')->orderby('paixu')->whereIn('id',$arr2)->get();
        }

        if(Auth::guard('admin')->user()->dengji === 1){
            $area3 = db::table('area')->where('dengji','=','3')->orderby('paixu')->get();
        }else{
            $area3 = db::table('area')->where('dengji','=','3')->orderby('paixu')->whereIn('id',$arr2)->get();
        }

        $action = $this->getCurrentAction();
        view()->share(['menu1'=>$menu1,'menu2'=>$menu2,'area1'=>$area1,'area2'=>$area2,'area3'=>$area3,'action'=>$action]);
        return $next($request);
    }

    /**
     * 获取当前控制器与方法
     *
     * @return array
     */
    public function getCurrentAction()
    {
        $action = \Route::current()->getActionName();
        //dd($action);
        //list($class, $method) = explode('@', $action);
        //return ['controller' => $class, 'method' => $method];
        return $action;
    }

}
